package com.alex.xmlyfm.fragments.album;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alex.mylibrary.tasks.TaskCallBack;
import com.alex.mylibrary.tasks.TaskResult;
import com.alex.xmlyfm.Constants;
import com.alex.xmlyfm.R;
import com.alex.xmlyfm.adapters.AlbumDetailAdapter;
import com.alex.xmlyfm.entities.albumdetail.AlbumDetailHeader;
import com.alex.xmlyfm.entities.albumdetail.AlbumDetailTrack;
import com.alex.xmlyfm.services.MusicService;
import com.alex.xmlyfm.tasks.AlbumDetailTask;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class AlbumDetailFragment extends Fragment implements AbsListView.OnScrollListener, AdapterView.OnItemClickListener{

    private List<AlbumDetailTrack> tracks;
    private ListView listView;
    private AlbumDetailAdapter adapter;
    private boolean isBottom;
    private AlbumDetailHeader header;
    private TextView txtHeaderTitle;
    private TextView txtHeaderSummary;
    private ImageView imageHeaderIcon;
    private Intent musicIntent;
    private ServiceConnection connection;
    private MusicService.MusicBinder musicBinder;

    private Handler handler = new Handler();
    private int numFlag;
    private boolean isBind;
    private LinearLayout linearLayout;
    private LinearLayout linearLayoutUp;

    public AlbumDetailFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_album_detial, container, false);

        linearLayoutUp = (LinearLayout) ret.findViewById(R.id.album_detial_up_layout);
        listView = (ListView) ret.findViewById(R.id.album_list);
        return ret;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Intent intent = getActivity().getIntent();
        long albumId = intent.getLongExtra(Constants.ALBUM_ID, -1);




        AlbumDetailTask task = new AlbumDetailTask(new TaskCallBack() {
            @Override
            public void onTaskFinished(TaskResult result) {

                Object data = result.datas[1];
                header = (AlbumDetailHeader) result.datas[0];
                txtHeaderTitle.setText(header.getTitle());
                txtHeaderSummary.setText(header.getIntro());
                Picasso.with(getContext()).load(header.getCoverOrigin()).into(imageHeaderIcon);

                tracks.clear();
                tracks.addAll((LinkedList<AlbumDetailTrack>) data);
                adapter.notifyDataSetChanged();

                ArrayList<String> trackMp3s = new ArrayList<>();

                int size = tracks.size();
                for (int i = 0; i < size; i++) {
                    trackMp3s.add(tracks.get(i).getPlayPathAacv164());
                }


                musicIntent = new Intent(getContext(), MusicService.class);
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("mp3List", trackMp3s);
                musicIntent.putExtra(Constants.ACTION_MUSIC_PLAY, trackMp3s);


                // 开启MUSIC 服务
                getActivity().startService(musicIntent);


//                numFlag = 0;
//
//                connection = new ServiceConnection() {
//                    @Override
//                    public void onServiceConnected(ComponentName name, IBinder service) {
//                        musicBinder = (MusicService.MusicBinder) service;
//
//                        new Thread(){
//                            @Override
//                            public void run() {
//                                while (true){
//                                    try {
//                                        Thread.sleep(200);
//                                        for (AlbumDetailTrack track : tracks) {
//                                            track.setIsPlay(false);
//                                        }
//                                        tracks.get(musicBinder.getPosition()-1).setIsPlay(musicBinder.isPlay());
//
//                                        handler.post(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                if (tracks.get(musicBinder.getPosition()-1).isPlay() == true){
//                                                    numFlag++;
//                                                }
//                                                if (numFlag > 2){
//                                                    adapter.notifyDataSetChanged();
//                                                }
//                                            }
//                                        });
//
//                                    } catch (InterruptedException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                        }.start();
//
//                    }
//
//
//
//                    @Override
//                    public void onServiceDisconnected(ComponentName name) {
//
//                    }
//                };


                //绑定
                isBind = getActivity().bindService(musicIntent, connection, Context.BIND_AUTO_CREATE);




            }
        });

        numFlag = 0;

        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                musicBinder = (MusicService.MusicBinder) service;

                new Thread(){
                    @Override
                    public void run() {
                        while (true){
                            try {
                                Thread.sleep(200);
                                for (AlbumDetailTrack track : tracks) {
                                    track.setIsPlay(false);
                                }
                                tracks.get(musicBinder.getPosition()-1).setIsPlay(musicBinder.isPlay());

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (tracks.get(musicBinder.getPosition()-1).isPlay() == true){
                                            numFlag++;
                                        }
                                        if (numFlag < 2){
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                });

                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();

            }




            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };




        task.execute(albumId + "");
        tracks = new LinkedList<>();
        adapter = new AlbumDetailAdapter(tracks, getContext());



        Button button = new Button(getContext());
        button.setText("加载更多");
        RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.fragment_album_detail_header, listView, false);
        listView.addHeaderView(relativeLayout);

        linearLayout = (LinearLayout) relativeLayout.findViewById(R.id.album_detail_layout);
        linearLayoutUp.setVisibility(View.INVISIBLE);




        txtHeaderTitle = (TextView) relativeLayout.findViewById(R.id.txt_header_title);
        txtHeaderSummary = (TextView) relativeLayout.findViewById(R.id.txt_header_summary);
        imageHeaderIcon = (ImageView) relativeLayout.findViewById(R.id.img_header_title);

        listView.addFooterView(button);

        listView.setAdapter(adapter);


        listView.setOnScrollListener(this);

        listView.setOnItemClickListener(this);



    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isBind){
            getActivity().unbindService(connection);
        }
    }

    public boolean isPlaying(){
        boolean ret = false;
        if(musicBinder != null){
            ret = musicBinder.isPlay();
        }
        return ret;
    }




    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (isBottom){

        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        isBottom = (firstVisibleItem + visibleItemCount) == totalItemCount;
        int[] location = new int[2];
        linearLayout.getLocationInWindow(location);
        int y = location[1];
        Log.d("albumDetail","  "+y);
        if (y <= 24){
            linearLayoutUp.setVisibility(View.VISIBLE);

        }else {
            linearLayoutUp.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        musicIntent.putExtra(Constants.ACTION_MUSIC_PLAY_CURRENT,position-1);
        getActivity().startService(musicIntent);
    }


}
